<?php

App::uses('AppController', 'Controller');

/**
 * CoreGroups Controller
 *
 * @property CoreGroup $CoreGroup
 */
class CoreGroupsController extends AppController {

    static $iconCls = "users";

    /**
     * index method
     *
     * @return void
     */
    public function index() {
        $this->CoreGroup->recursive = 0;
        $this->set('coreGroups', $this->paginate());
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($id = null) {
        if (!$this->CoreGroup->exists($id)) {
            throw new NotFoundException(__('Invalid core group'));
        }
        $options = array('conditions' => array('CoreGroup.' . $this->CoreGroup->primaryKey => $id));
        $this->set('coreGroup', $this->CoreGroup->find('first', $options));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add() {
        if ($this->request->is('post')) {
            $this->CoreGroup->create();
            if ($this->CoreGroup->save($this->request->data)) {
                $id = $this->CoreGroup->getInsertID();
                App::import('Model', 'CorePrivilegesGroupsModule');
                $corePrivilegesGroupsModule = new CorePrivilegesGroupsModule();
                $corePrivilegesGroupsModule->create();
                // delete all modules for this block
                $data = array('CorePrivilegesGroupsModule.core_groups_id' => $id);
                // delete the data
                $corePrivilegesGroupsModule->deleteAll($data);
                // save each module
                //var_dump($this->request->data);exit;
                foreach ($this->request->data['CoreGroup']['CoreModuleRead'] as $value) {
                    $corePrivilegesGroupsModule->create();

                    $privilegesGroupsData = explode("_", $value);
                    $read = $write = $admin = 0;
                    if (!empty($privilegesGroupsData[1])) {
                        if ($privilegesGroupsData[0] == 'r') {
                            $read = 1;
                        } else if ($privilegesGroupsData[0] == 'w') {
                            $write = 1;
                        } else {
                            $admin = 1;
                        }

                        $data = array(
                            'CorePrivilegesGroupsModule' => array(
                                'core_modules_id' => $privilegesGroupsData[1],
                                'core_groups_id' => $id,
                                'copg_read' => $read,
                                'copg_write' => $write,
                                'copg_admin' => $admin
                            )
                        );
                        // save the data
                        $corePrivilegesGroupsModule->save($data);
                    }
                }
                $this->Session->setFlash(__('The core group has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The core group could not be saved. Please, try again.'));
            }
        }
        App::import('Controller', 'CoreModules');
        $coreModule = new CoreModulesController();
        $modules = $coreModule->listModulesFromDB();
        $this->set(compact('modules'));
    }

    public function getGrupoPorNome($nome) {
        $options = array('conditions' => array('cogr_name' => $nome));
        $object = $this->CoreGroup->find('first', $options);
        return $object;
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function edit($id = null) {
        if (!$this->CoreGroup->exists($id)) {
            throw new NotFoundException(__('Invalid core group'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->CoreGroup->save($this->request->data)) {
                App::import('Model', 'CorePrivilegesGroupsModule');
                $corePrivilegesGroupsModule = new CorePrivilegesGroupsModule();
                $corePrivilegesGroupsModule->create();
                // delete all modules for this block
                $data = array('CorePrivilegesGroupsModule.core_groups_id' => $id);
                // delete the data
                $corePrivilegesGroupsModule->deleteAll($data);
                // save each module
                //var_dump($this->request->data);exit;
                if (!empty($this->request->data['CoreGroup']['CoreModuleRead'])) {
                    foreach ($this->request->data['CoreGroup']['CoreModuleRead'] as $value) {
                        $corePrivilegesGroupsModule->create();

                        $privilegesGroupsData = explode("_", $value);
                        $read = $write = $admin = 0;
                        if (!empty($privilegesGroupsData[1])) {
                            if ($privilegesGroupsData[0] == 'r') {
                                $read = 1;
                            } else if ($privilegesGroupsData[0] == 'w') {
                                $write = 1;
                            } else {
                                $admin = 1;
                            }

                            $data = array(
                                'CorePrivilegesGroupsModule' => array(
                                    'core_modules_id' => $privilegesGroupsData[1],
                                    'core_groups_id' => $id,
                                    'copg_read' => $read,
                                    'copg_write' => $write,
                                    'copg_admin' => $admin
                                )
                            );
                            // save the data
                            $corePrivilegesGroupsModule->save($data);
                        }
                    }
                }
                $this->Session->setFlash(__('The core group has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The core group could not be saved. Please, try again.'));
            }
        } else {
            $options = array('conditions' => array('CoreGroup.' . $this->CoreGroup->primaryKey => $id));
            $this->request->data = $this->CoreGroup->find('first', $options);
        }
        App::import('Controller', 'CorePrivilegesGroupsModules');
        $corePrivilegesGroupsModule = new CorePrivilegesGroupsModulesController();
        $this->set(compact('corePrivilegesGroupsModule'));
        //$selected = $corePrivilegesGroupsModule->getModulesIdFromPrivilegesGroup($id);
        //$selected = array(2,4);
        //$this->set(compact('selected'));
        App::import('Controller', 'CoreModules');
        $coreModule = new CoreModulesController();
        $modules = $coreModule->listModulesFromDB();
        $this->set(compact('modules'));
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @throws MethodNotAllowedException
     * @param string $id
     * @return void
     */
    public function delete($id = null) {
        $this->CoreGroup->id = $id;
        if (!$this->CoreGroup->exists()) {
            throw new NotFoundException(__('Invalid core group'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->CoreGroup->delete()) {
            $this->Session->setFlash(__('Core group deleted'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Core group was not deleted'));
        $this->redirect(array('action' => 'index'));
    }

    public function listGroupsFromDB() {
        $groups = $this->CoreGroup->find('all');
        if (empty($groups))
            return array();
        $list = array();
        foreach ($groups as $value) {
            $list[$value["CoreGroup"]["id"]] = $value["CoreGroup"]["cogr_name"];
        }
        return $list;
    }

    public function getPublicPermitions($user = null) {
        // get the public group
        $this->CoreGroup->setBypass(true);
        $options = array('conditions' => array('CoreGroup.cogr_public' => 1));
        $data = $this->CoreGroup->find('first', $options);
        $id = $data["CoreGroup"]["id"];
        App::import('Controller', 'CoreUsersGroups');
        $coreUsersGroupsController = new CoreUsersGroupsController();
        $coreUsersGroupsController->CoreUsersGroup->setBypass(true);
        $permitions = $coreUsersGroupsController->getModulesPermitionsFromGroup($id);
        $coreUsersGroupsController->CoreUsersGroup->setBypass(false);
        $this->CoreGroup->setBypass(false);
        if (empty($user['id'])) {
            $user['id'] = 0;
            $user['cous_user'] = null;
        }
        return array('id' => $user['id'], 'groups' => array($id), 'cous_user' => $user['cous_user'], 'permitions' => $permitions);
    }

    public function getByPassPermitions() {
        // get the public group
        $this->CoreGroup->setBypass(true);
        $options = array('conditions' => array('CoreGroup.cogr_public' => 1));
        $data = $this->CoreGroup->find('first', $options);
        $id = $this->byPassGetAllGroupsID();
        $permitions = $this->byPassPermitions();
        $this->CoreGroup->setBypass(false);
        if (empty($user['id'])) {
            $user['id'] = 0;
            $user['cous_user'] = null;
        }
        return array('id' => 1, 'groups' => $id, 'cous_user' => 'ByPassedUser', 'permitions' => $permitions);
    }

    /**
     * if this is called the user will have admin permition in all modules
     */
    private function byPassPermitions() {
        App::import('Controller', 'CoreModules');
        $coreModulesController = new CoreModulesController();
        $coreModulesController->CoreModule->setBypass(true);
        $data = $coreModulesController->CoreModule->find('all');
        $coreModulesController->CoreModule->setBypass(false);
        $modules = array();
        foreach ($data as $value) {
            // get permitions
            $modules[$value["CoreModule"]["id"]] = 'admin';
        }
        return $modules;
    }

    private function byPassGetAllGroupsID() {
        $this->CoreGroup->setBypass(true);
        $data = $this->CoreGroup->find('all');
        $this->CoreGroup->setBypass(false);
        $groupsId = array();
        foreach ($data as $value) {
            // get permitions
            $groupsId[] = $value["CoreGroup"]["id"];
        }
        return $groupsId;
    }


}

